﻿using System.Windows;
using Omniscient.Foundation.ApplicationModel;
using Omniscient.Foundation.ApplicationModel.Modularity;
using Omniscient.Foundation.ApplicationModel.Presentation;
using Omniscient.Foundation.ApplicationModel.Security;
using Omniscient.Foundation.Security;
using Omniscient.TimeTracker.BusinessModel.Security;

namespace Omniscient.TimeTracker.Security
{
    public class CredentialServiceExtender : IExtender<ICredentialServiceExtenderContract>, ICredentialServiceExtenderContract
    {
        private IPresentationController _controller;

        public CredentialServiceExtender(IPresentationController presController)
        {
            _controller = presController;
        }

        public ICredentialServiceExtenderContract GetImplementation() { return this; }

        #region ICredentialServiceExtenderContract Members

        public void NegociateAuthentication(SecurePrincipal principal)
        {
            // Display login prompt
            LoginPrompt prompt = new LoginPrompt();
            prompt.Owner = ApplicationManager.Current.Shell as Window;
            prompt.ShowDialog();

            if (prompt.UserCredential == null) return;

            // Decrypt the password
            string password = SecureStringConverter.FromSecureString(prompt.UserCredential.Password);

            // Retrieve the corresponding resource
            ISecurityService security;
            security = ApplicationManager.Current.ObjectContainer.Get<ISecurityService>();
            SecurePrincipal authenticated;
            authenticated = security.GetAuthenticatedUser(prompt.UserCredential.UserName, password);

            // Fill the principal with valid roles and identity
            principal.Promote(authenticated.AllRoles);
            principal.Identity.Promote(authenticated.Identity.Name, prompt.UserCredential.Password, authenticated.Identity.AuthenticationType);
        }

        #endregion
    }
}
